import 'package:flutter/material.dart';

class LoadingView extends StatefulWidget {
  final Widget child;
  final Function loadData;
  const LoadingView({
    super.key,
    required this.child,
    required this.loadData,
  });

  @override
  State<LoadingView> createState() => _LoadingViewState();
}

class _LoadingViewState extends State<LoadingView> {
  late Future<dynamic>? futureLoad;

  @override
  void initState() {
    super.initState();
    futureLoad = _loadData();
  }

  Future<dynamic> _loadData() async {
    await widget.loadData();
    return 'ok';
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: futureLoad,
      builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
        if (snapshot.hasError) {
          return Center(child: Text('发生错误: ${snapshot.error}'));
        }
        switch (snapshot.connectionState) {
          case ConnectionState.waiting:
            return const Center(child: CircularProgressIndicator());
          case ConnectionState.active:
          case ConnectionState.done:
            return widget.child;
          case ConnectionState.none:
          default:
            return const Center(child: Text('请求失败'));
        }
      },
    );
  }
}
